<template>
    <div class="sku-list">
        <div class="loading-box" v-if="loading">
            <bi-icon loading ></bi-icon>
        </div>

        <div class="sku-param-list" >
            <div class="sdk-param-item" v-for="(variantItem) in variantItemList" :key="variantItem.item_id" >
                <div class="sdk-param-item-title">
                    {{variantItem.title}}
                </div>
                <div class="sdk-param-item-content">
                    <goods-sku-param :title="variantItem.title" :image="variantItem.image==1" :list="paramList[variantItem.title]" @change="handleChangeParam" ></goods-sku-param>
                </div>
            </div>
        </div>

        <div class="sku-list" v-if="skuList && skuList.length>0">
            <bi-table :data="skuList" :loading="skuloading">
                <bi-table-column label="" name="name" width="35" v-slot="{index}" >
                    <bi-icon data="fa-clock-o" class="status-icon "  v-if="skuCheck[index] =='null'" ></bi-icon>
                    <bi-icon data="fa-check" class="text-success status-icon" v-if="skuCheck[index] =='yes'" ></bi-icon>
                    <bi-icon data="fa-close" class="text-danger status-icon"  v-if="skuCheck[index] =='no'" ></bi-icon>
                </bi-table-column>
                <bi-table-column label="规格" name="name" width="200" v-slot="{row,index}" >
                    {{row.name}}
                </bi-table-column>
                <bi-table-column label="默认" width="50" v-slot="{row,index}" >
                    <bi-icon data="fa-star-o" @click="handleDefaultChange(index)" class="default-icon icon-btn" :class="{'checked':defaultValueRow==index}" ></bi-icon>
                </bi-table-column>
                <bi-table-column label="价格 *" name="price"  width="100" v-slot="{row,index}" >
                    <bi-input v-model="skuList[index].price"  type="number" ></bi-input>
                </bi-table-column>
                <bi-table-column label="库存 *" name="stock" width="100"  v-slot="{row,index}">
                    <bi-input v-model="skuList[index].stock" type="number"></bi-input>
                </bi-table-column>
                <bi-table-column label="重量 " name="weight" width="100" v-slot="{row,index}">
                    <bi-input  v-model="skuList[index].weight" type="number"></bi-input>
                </bi-table-column>
                
                <bi-table-column label="条形码 *" name="barcode"  v-slot="{row,index}"  width="150" >
                    <bi-input v-model="skuList[index].barcode"></bi-input>
                </bi-table-column>
                <bi-table-column label="销售标题" name="title"  v-slot="{row,index}" >
                    <bi-input v-model="skuList[index].title"></bi-input>
                </bi-table-column>
                <bi-table-column label="商品参数" name="title"  v-slot="{row,index}"  width="80" >
                    <bi-button>设置</bi-button>
                </bi-table-column>
            </bi-table>
        </div>

    </div>
</template>


<script>
import goodsSkuParam from './goods-sku-param.vue';
export default{
    emits: ['change'],
    components:{
        goodsSkuParam
    },
    data(){

        let paramList = this.param;
        let skuList = this.sdk;

        return {
            variantItemList:[],
            paramList,
            skuList,
            skuCheck:[],
            loading:true,
            skuloading:false,
            defaultValueRow:0
        }
    },
    props:{
        variant:[Number,String],
        param:{
            type:Object,
            default:{}
        },
        sku:{
            type:Array,
            default:[]
        }
    },
    watch:{
        variant(val){
            this.load();
        },
        skuList:{
            deep:true,
            handler(val){            
                for(let i=0;i<this.skuList.length;i++){
                    let sku = this.skuList[i];
                    let check  = 'yes';
                    if (sku.price == 0 && sku.stock == 0 && sku.weight == '' && sku.title == '' && sku.barcode == ''){
                        check = 'null';
                    }else{
                        if (sku.price == 0){
                            check = 'no';
                        }

                        //判断是不是数字
                        if (isNaN(sku.price) || parseFloat(sku.price) <= 0 ){
                            check = 'no';
                        }

                        
                        if (parseFloat(sku.stock) < 0){
                            check = 'no';
                        }
                        
                        if (isNaN(sku.stock) || parseFloat(sku.stock) < 0 ){
                            check = 'no';
                        }

                        if (sku.weight!='' && (isNaN(sku.weight) || parseFloat(sku.weight) <= 0)){
                            check = 'no';
                        }
                    
                        if (sku.barcode == ''){
                            check = 'no';
                        }
                    }

                    this.skuCheck[i] = check;
                }
            }
        }
    },
    methods:{
        load(){
            this.$ajax({
                url:this.$url({'app':'shop','controller':'admin.variant','action':'itemList'}),
                data:{
                    goods_id:this.goods,
                    variant_id:this.variant
                },
                success:(data)=>{
                    this.variantItemList = data;
                    data.map(item=>{
                       if (this.paramList[item.title]==undefined){
                           this.paramList[item.title] = [];
                       }
                    });
                    this.flashSkuList();
                    this.loading = false;
                }
            })
        },
       
        flashSkuList(){
            this.skuloading = true;
            this.skuList = [];
            let paramListlength = this.variantItemList.length;
            
            let skuMake = (data = [],index=0) =>{
                let paramName = this.variantItemList[index].title;
                let list  = this.paramList[paramName];
                let zindex = 0;
                for(let i=0;i<list.length;i++){
                    let newData = JSON.parse(JSON.stringify(data));
                    let item = list[i];
                    if (item.title !=''){
                        newData.push({
                            zindex:zindex++,
                            image:item.image??'',
                            name:item.title,
                        });
                    }

                    if (index+1 == paramListlength){
                        let value  = getValue(newData);
                        this.skuCheck.push(
                            value.status
                        );
                        delete value.status;
                        
                        this.skuList.push({
                            indexs:getIndex(newData),
                            name:getName(newData),
                            ...value,
                        });
                    }else{
                        skuMake(newData,index+1);
                    }
                }
            }

            let getName = (data)=>{
                let name = [];
                data.map((item)=>{
                    name.push(item.name);
                });
                return name.join(',');
            }

            let getIndex = (data)=>{
                let indexs = [];
                data.map((item)=>{
                    indexs.push(item.zindex);
                });

                return indexs.join('_');
            }
            
            let getValue = (data)=>{
                for(let i=0;i<this.sku.length;i++){
                    let skuItem = this.sku[i];
                    let namelist = skuItem.name.split(',');
                    if (namelist.length == data.length){
                        let count = data.length;
                        data.map(item=>{
                            if (namelist.indexOf(item.name) != -1){
                                count--;
                            }
                        })
                        if (count == 0){
                            console.log(skuItem);
                            return  {
                                status:'yes',
                                default_value:skuItem.default_value,
                                price:skuItem.price,
                                stock:skuItem.stock,
                                weight:skuItem.weight,
                                title:skuItem.title,
                                barcode:skuItem.barcode
                            };
                        }
                    }
                }

                return {
                    status:'null',
                    default_value:0,
                    price:0,
                    stock:0,
                    weight:'',
                    title:'',
                    barcode:''
                }
            }

            skuMake();
            
            this.$nextTick(()=>{

                //如果没有默认值，就将第一个设为默认值
                let count  = 0;
                this.skuList.map((item,index)=>{
                    if (item.default_value == 1) {
                        count ++;
                        this.defaultValueRow = index;
                    };
                });

                if (count==0){
                    this.skuList[0].default_value  =1;
                    this.defaultValueRow = 0;
                }
                this.skuloading = false;
            });
            
        },

        handleChangeParam(title,value){
            this.paramList[title] = value;
            this.flashSkuList();
            this.change();
        },
        change(){
            this.$emit('change',this.paramList,this.skuList);
        },
        getData(){


            let  sku = JSON.parse(JSON.stringify(this.skuList));
            return {sku_param:this.paramList,sku};
        },
        check(){
           for(let name in this.paramList){
                let param = this.paramList[name];
                let variant = this.variantItemList.filter(item=>{
                    return item.title == name;
                })
                if (param.length == 0) {
                    this.$alert('请设置'+name+'参数的值');
                    return false;
                }

                for(let i=0;i<param.length;i++){
                    let item = param[i];
                    if (item.title == '') {
                        this.$alert('请设置'+name+'参数的值');
                        return false;
                    }

                    if (variant.image ==1 && item.image == ''){
                        this.$alert('请设置'+name+'参数的图片');
                        return false;
                    }
                }
           }

           let skuCount = 0;

           for(let i=0;i<this.skuCheck.length;i++){
                if (this.skuCheck[i] == 'no'){
                    this.$alert('请给规格'+this.skuList[i].name+'设置正确的值');
                    return false;        
                }

                if (this.skuCheck[i] == 'yes'){
                    skuCount++;
                }
           }

           if (skuCount == 0){
                this.$alert('至少要有一条规格');
                return false;
           }
        
           return true;
        },
        handleDefaultChange(index){
            this.defaultValueRow = index;
            this.skuList.map((item,itemIndex)=>{
                if (index==itemIndex){
                    item.default_value = 1;
                }else{
                    item.default_value = 0;
                }
            })
        }
        

    },
    mounted(){
        this.load();
    }
}
</script>


<style >
.loading-box{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}
.status-icon{
    font-size: 18px;
    color: var(--bs-gray-400);
}

.default-icon{
    font-size: 18px;
}

.default-icon.checked{
    color: var(--bs-warning);
}

</style>